package com.example.douyin.controller;

import com.example.douyin.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author dangwen1
 * @date 2022年02月21日 21:27
 * @description
 */
@RestController
@Slf4j
@RequestMapping(("dc"))
public class DcAppController {
    /**
     * 1.@Resource的作用相当于@Autowired，只不过@Autowired按byType自动注入，而@Resource默认按 byName自动注入罢了
     */
    @Resource
    private RestTemplate restTemplate;

    private final String baseUrl = "http://www.dianchouapp.com";

    @PostMapping("gotoBuy")
    public List<DcAppOrderPayDetail> gotoBuy(DcAppGotoByVo dcAppGotoByVo) {
        List<DcAppOrderPayDetail> list = new ArrayList<>();
        if (StringUtils.isEmpty(dcAppGotoByVo.getUserName()) || StringUtils.isEmpty(dcAppGotoByVo.getPassword())) {
            log.info("用户名或者密码不能为空");
            return list;
        }
        String loginUrl = "http://www.dianchouapp.com/app/user/loginNormal";
        MultiValueMap<String, String> loginMap = new LinkedMultiValueMap<>();
        loginMap.add("userName", dcAppGotoByVo.getUserName());
        loginMap.add("password", dcAppGotoByVo.getPassword());
        HttpHeaders httpHeaders = getHttpHeaders();
        HttpEntity<MultiValueMap<String, String>> loginEntity = new HttpEntity<>(loginMap, httpHeaders);
        DcAppLoginVo dcAppLoginVo = restTemplate.postForObject(loginUrl, loginEntity, DcAppLoginVo.class);
        log.info("----登录出参：{}", dcAppLoginVo);
        String tokenId = "";
        if (Objects.nonNull(dcAppLoginVo) && "200".equals(dcAppLoginVo.getErrorCode())) {
            DcAppLoginDetailVo detail = dcAppLoginVo.getDetail();
            tokenId = detail.getTokenId();

            MultiValueMap<String, String> searchListMap = new LinkedMultiValueMap<>();
            searchListMap.add("commodityName", dcAppGotoByVo.getCommodityName());
            searchListMap.add("businessType", dcAppGotoByVo.getBusinessType());
            String pageListUrl = "http://www.dianchouapp.com/app/shopBuy/listPage?tokenId=" + tokenId;
            HttpEntity<MultiValueMap<String, String>> searchListEntity = new HttpEntity<>(searchListMap, httpHeaders);
            DcAppPageListVo pageListVo = restTemplate.postForObject(pageListUrl, searchListEntity, DcAppPageListVo.class);
            log.info("----查询列表出参：{}", pageListVo);
            if (Objects.nonNull(pageListVo) && "200".equals(pageListVo.getErrorCode())) {
                DcAppPageListDetailVo pageListVoDetail = pageListVo.getDetail();
                List<DcAppSkuInfoVo> recordList = pageListVoDetail.getRecordList();

                Double setPrice = dcAppGotoByVo.getSetPrice();
                for (DcAppSkuInfoVo dcAppSkuInfoVo : recordList) {
                    // 价格合理，开始下单
                    if (Objects.nonNull(dcAppSkuInfoVo) && dcAppSkuInfoVo.getPrice() < setPrice) {
                        Long buyMainId = dcAppSkuInfoVo.getBuyMainId();
                        String skuDetailUrl = "http://www.dianchouapp.com/app/shopBuy/detail?id=" + buyMainId + "&tokenId=" + tokenId;
                        ResponseEntity<DcAppSkuVo> skuDetailResp = restTemplate.getForEntity(skuDetailUrl, DcAppSkuVo.class);
                        log.info("----查询详情出参：{}", skuDetailResp);
                        DcAppSkuVo body = skuDetailResp.getBody();
                        if (Objects.nonNull(body) && Objects.nonNull(body.getDetail())) {
                            DcAppSkuDetailVo skuDetailVo = body.getDetail();
                            List<DcAppSkuStockInfoVo> skuStockInfoVos = skuDetailVo.getShopBuySpecAndStockVoList();
                            for (DcAppSkuStockInfoVo skuStockInfoVo : skuStockInfoVos) {
                                String buySpecId = skuStockInfoVo.getBuySpecId();
                                Integer stock = skuStockInfoVo.getStock();
                                Double price = skuStockInfoVo.getPrice();
                                if (price < setPrice) {
                                    // 价格合理，拿到下单ID，直接去下单
                                    String gotoBuyUrl = "http://www.dianchouapp.com/app/orderV2/preOrderConfirm?tokenId=" + tokenId;
                                    MultiValueMap<String, String> gotoBuyMap = new LinkedMultiValueMap<>();
                                    String preOrderVo = "{\"ableAppWeixinMini\":\"1\",\"goods\":[{\"buySpecId\":\"" + buySpecId + "\",\"counts\":" +
                                            stock + "}],\"latitude\":0,\"longitude\":0,\"platform\":\"app\",\"proxyOrder\":false,\"reserveId\":0,\"liveRecordId\":\"\"}";
                                    gotoBuyMap.add("preOrderVo", preOrderVo);
                                    HttpEntity<MultiValueMap<String, String>> gotoBuyEntity = new HttpEntity<>(gotoBuyMap, httpHeaders);
                                    DcAppOrderConfirmVo orderConfirmResp = restTemplate.postForObject(gotoBuyUrl, gotoBuyEntity, DcAppOrderConfirmVo.class);
                                    log.info("----去支付出参：{}", orderConfirmResp);
                                    if (Objects.nonNull(orderConfirmResp) && Objects.nonNull(orderConfirmResp.getDetail())) {
                                        DcAppOrderConfirmDetailVo confirmVo = orderConfirmResp.getDetail();
                                        String addressId = confirmVo.getAddressId();
                                        String createOrderVo = "{\"addressId\":\"" + addressId + "\",\"dianchouPayAmount\":0,\"goods\":[{\"buySpecId\":\"" +
                                                buySpecId + "\",\"counts\":" + stock + "}],\"payLater\":false,\"payType\":\"alipay\",\"platSource\":\"ANDROID\"," +
                                                "\"platform\":\"app\",\"proxyOrder\":false,\"receiveType\":\"DELIVERY\",\"reserveId\":0,\"version\":\"1.0\",\"liveRecordId\":\"\"}";
                                        String orderPayUrl = "http://www.dianchouapp.com/app/orderV2/orderPay?tokenId=" + tokenId;
                                        MultiValueMap<String, String> orderPayMap = new LinkedMultiValueMap<>();
                                        orderPayMap.add("createOrderVo", createOrderVo);
                                        HttpEntity<MultiValueMap<String, String>> orderPayEntity = new HttpEntity<>(orderPayMap, httpHeaders);
                                        DcAppOrderPayVo orderPayResp = restTemplate.postForObject(orderPayUrl, orderPayEntity, DcAppOrderPayVo.class);
                                        log.info("----确认支付出参：{}", orderPayResp);
                                        if (Objects.nonNull(orderPayResp) && "200".equals(orderPayResp.getErrorCode()) && Objects.nonNull(orderPayResp.getDetail())) {
                                            DcAppOrderPayDetail payRespDetail = orderPayResp.getDetail();
                                            if (Objects.nonNull(confirmVo.getFarmers())){
                                                List<DcAppOrderConfirmDetailFarmersVo> farmers = confirmVo.getFarmers();
                                                List<DcAppOrderConfirmDetailFarmersGoodsVo> goods = new ArrayList<>();
                                                for (DcAppOrderConfirmDetailFarmersVo farmer : farmers) {
                                                    List<DcAppOrderConfirmDetailFarmersGoodsVo> farmerGoods = farmer.getGoods();
                                                    goods.addAll(farmerGoods);
                                                }
                                                payRespDetail.setGoods(goods);
                                            }
                                            list.add(payRespDetail);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return list;
    }

    private HttpHeaders getHttpHeaders() {
        // 模拟form表单发送请求
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        return httpHeaders;
    }


}
